package net.test.piggy.controller;

import net.test.piggy.component.FileSaveHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UploadController {
    @Resource
    private FileSaveHandler fileSaveHandler;

    @ResponseBody
    @PostMapping("upload")
    public Map<String,Object> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        List<Map<String,Object>> fileList = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                String filePath = fileSaveHandler.uploadFile(file);
                if(filePath!=null){
                    Map<String,Object> map = new HashMap<>();
                    map.put("fileName",file.getName());
                    map.put("filePath",filePath);
                    fileList.add(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new HashMap<String,Object>(){{this.put("data",fileList);}};
    }



}
